//
//  MTShouQuanVC.m
//  met
//
//  Created by 李晓俊 on 2019/5/8.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTShouQuanVC.h"
#import <CoreLocation/CoreLocation.h>
#import "CYLMainRootViewController.h"
#import "ZLAdvertView.h"
@interface MTShouQuanVC ()<CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *goBut;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UIImageView *backImage;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *height;

@property (weak, nonatomic) IBOutlet UIImageView *shouquanIamge;

@end

@implementation MTShouQuanVC {
    CLLocationManager * _locationManager;       // 位置管理器
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self wr_setNavBarBackgroundAlpha:0];
    self.bgView.layer.borderWidth = 2;
    self.bgView.layer.borderColor = KBlackColor.CGColor;
    self.goBut.layer.borderWidth = 2;
    self.goBut.layer.borderColor = KBlackColor.CGColor;
//    self.height.constant = 15 + StatusHeight;
//    self.goBut.backgroundColor = HEXCOLOR(0xCDD3DB);
    
//    self.backImage.userInteractionEnabled = YES;
//    UITapGestureRecognizer *back = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(returnClick)];
//    [self.backImage addGestureRecognizer:back];
    
    self.shouquanIamge.userInteractionEnabled = YES;
    UITapGestureRecognizer *shouquan = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shouquanClick)];
    [self.shouquanIamge addGestureRecognizer:shouquan];
    
    self.bgView.hidden = YES;
    
    if (_locationManager == nil) {
        _locationManager = [CLLocationManager new];
    }
}
- (void)returnClick {
    [self.navigationController  popViewControllerAnimated:YES];
}
- (void)shouquanClick {
    
    if (_locationManager != nil) {
        _locationManager.delegate = self;
        // 请求“使用期间”使用定位服务
        [_locationManager requestAlwaysAuthorization];
    }
    NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
    [dataUser setObject:@"1" forKey:@"dingwei"];
    [dataUser synchronize];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self location];
//    [self setupAdvert];
}
//定位权限
- (void)location {
    if ([CLLocationManager locationServicesEnabled]) {
        // 判断用户是否允许程序获取位置权限
        if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedAlways) {
            //[CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse||
            //用户允许获取位置权限
            [self pushHome];

        }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse) {
            //部分权限
            self.bgView.hidden = NO;
            self.shouquanIamge.hidden = YES;
            [self pushHome];
        } else {
            //用户还未开启用户权限
            DLog(@"jujue");
//
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            NSString *dingwei = [userDefault objectForKey:@"dingwei"];
            if ([dingwei isEqualToString:@"1"]) {
                //用户拒绝开启用户权限
                self.bgView.hidden = NO;
                self.shouquanIamge.hidden = YES;
                [self pushHome];
            }else {
               
            }
        }
    }else {
        [self pushHome];
        //用户拒绝开启用户权限
        self.bgView.hidden = NO;
        self.shouquanIamge.hidden = YES;
    }
}
/** 定位服务状态改变时调用*/
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusAuthorizedAlways ) {
        DLog(@"获得所有授权");
//            [self pushHome];
    }else {
        self.bgView.hidden = NO;
        self.shouquanIamge.hidden = YES;
    }
}

- (IBAction)nextClick:(id)sender {
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if( [[UIApplication sharedApplication]canOpenURL:url] ) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)pushHome {
    UIWindow * window = [[UIWindow alloc] init];
    
    CYLMainRootViewController *rootViewController = [[CYLMainRootViewController alloc] init];
    window.rootViewController = rootViewController;
    self.window = window;
    [self.window makeKeyAndVisible];
}





/**
 *  设置启动页广告
 */
- (void)setupAdvert {
    
    // 1.判断沙盒中是否存在广告图片，如果存在，直接显示
    NSString *filePath = [self getFilePathWithImageName:[kUserDefaults valueForKey:adImageName]];
    
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (isExist) { // 图片存在
        ZLAdvertView *advertView = [[ZLAdvertView alloc] initWithFrame:CGRectMake(0, 0, kscreenWidth, kscreenHeight)
                                    ];
//        self.window.bounds];
        advertView.filePath = filePath;
        advertView.doneCLick = ^(NSString *n) {
             [self location];
        };
        [advertView show];
    }else {
         [self location];
    }
    
    // 2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告是否更新
    [self getAdvertisingImage];
}

/**
 *  判断文件是否存在
 */
- (BOOL)isFileExistWithFilePath:(NSString *)filePath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}
/**
 *  初始化广告页面
 */
- (void)getAdvertisingImage {
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            NSArray *ar = [data objectForKey:@"data"];
            if (ar.count>0) {
                NSString *imageUrl = [ar objectAtIndex:0];
                // 获取图片名:43-130P5122Z60-50.jpg
                NSArray *stringArr = [imageUrl componentsSeparatedByString:@"/"];
                NSString *imageName = stringArr.lastObject;
                
                // 拼接沙盒路径
                NSString *filePath = [self getFilePathWithImageName:imageName];
                BOOL isExist = [self isFileExistWithFilePath:filePath];
                if (!isExist){ // 如果该图片不存在，则删除老图片，下载新图片
                    [self downloadAdImageWithUrl:imageUrl imageName:imageName];
                }
            }
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc startPageFind];
    
    // TODO 请求广告接口
    // 这里原本应该采用广告接口，现在用一些固定的网络图片url代替
//    NSArray *imageArray = @[
//                            @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg",
//                            @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg",
//                            @"http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"
//                            ];
//    NSString *imageUrl = imageArray[arc4random() % imageArray.count];
    
    
}
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        NSString *filePath = [self getFilePathWithImageName:imageName]; // 保存文件的名称
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功
            NSLog(@"保存成功");
            [self deleteOldImage];
            [kUserDefaults setValue:imageName forKey:adImageName];
            [kUserDefaults synchronize];
            // 如果有广告链接，将广告链接也保存下来
        }else{
            DLog(@"保存失败");
        }
        
    });
}

/**
 *  删除旧图片
 */
- (void)deleteOldImage {
    
    NSString *imageName = [kUserDefaults valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

/**
 *  根据图片名拼接文件路径
 */
- (NSString *)getFilePathWithImageName:(NSString *)imageName {
    
    if (imageName) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    
    return nil;
}
@end
